package org.linlinjava.litemall.mechanismadmin.web;

import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.demo.trade.model.ExtendParams;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeQueryRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.model.result.AlipayF2FQueryResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.pagehelper.util.StringUtil;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.TradeStatus.AliTradeStatus;
import org.linlinjava.litemall.core.TradeStatus.WxTradeStatus;
import org.linlinjava.litemall.core.alipay.config.AliPayProperties;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.systemConfig.SystemConfig;
import org.linlinjava.litemall.core.util.CharUtil;
import org.linlinjava.litemall.core.util.ParseXmlUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.mechanismadmin.annotation.LoginAdmin;
import org.linlinjava.litemall.mechanismadmin.config.GetWxPayService;
import org.linlinjava.litemall.mechanismadmin.util.WxPlaceOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.alipay.demo.trade.config.Constants.SUCCESS;

@RestController
@RequestMapping("/mechanismadmin/user")
public class MechanismAdminUserController {
    private final Log logger = LogFactory.getLog(MechanismAdminUserController.class);

    @Autowired
    private  AliPayProperties aliPayProperties;

    @Autowired
    private GetWxPayService getWxPayService;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private AlipayTradeService alipayTradeService;

    @Autowired
    private PlatformTransactionManager txManager;

    @Autowired
    private LitemallUserService userService;

    @Autowired
    private LitemallWalletRecordService recordService;

    @Autowired
    private LitemallMechanismService mechanismService;

    @Autowired
    private LitemallConfigService configService;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private LitemallOrderService litemallOrderService;

    /**
     * 下载充值记录
     * @param adminId
     * @param addTime
     * @return
     */
    @GetMapping("/down")
    public Object totalList(@LoginAdmin Integer adminId,Integer mechanismId,String addTime){
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        LocalDateTime start = null;
        LocalDateTime end = null;
        if(!StringUtils.isEmpty(addTime)){
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            start = LocalDateTime.parse(addTime.split(",")[0],df);
            end = LocalDateTime.parse(addTime.split(",")[1],df);
        }
        List<LitemallWalletRecordVo> litemallWalletRecordVos = recordService.queryWalletRecordBills(mechanismId,start,end);
        List<Object> list = new ArrayList<>();
        if(litemallWalletRecordVos!=null){
           for(int i=0;i<litemallWalletRecordVos.size();i++){
               LitemallWalletRecordVo litemallWalletRecordVo = litemallWalletRecordVos.get(i);
               Byte type = litemallWalletRecordVo.getPayType();
               if(type==1){
                   litemallWalletRecordVo.setPayTypes("支付宝");
               }else if(type==2){
                   litemallWalletRecordVo.setPayTypes("微信");
               }else if(type==3){
                   litemallWalletRecordVo.setPayTypes("其他");
               }else {
                   litemallWalletRecordVo.setPayTypes("爱币");
               }
               list.add(litemallWalletRecordVo);
           }
        }
        Map<String, Object> data = new HashMap<>(1);
        data.put("items", litemallWalletRecordVos);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/list")
    public Object list(
        @LoginAdmin Integer adminId,
        String username,
        String mobile,
        @RequestParam(value = "page", defaultValue = "1") Integer page,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit,
        String sort,
        String order) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        List<LitemallUser> userList = userService.querySelective(username, mobile, page, limit, sort, order);
        int total = userService.countSeletive(username, mobile, page, limit, sort, order);
        Map<String, Object> data = new HashMap<>(2);
        data.put("total", total);
        data.put("items", userList);

        return ResponseUtil.ok(data);
    }

    @GetMapping("/lists")
    public Object list(
        @LoginAdmin Integer adminId,
        Integer mechanismId,
        @RequestParam(value = "page", defaultValue = "1") Integer page,
        @RequestParam(value = "limit", defaultValue = "10") Integer limit,
        String sort,
        String order) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        List<LitemallWalletRecordVo> walletRecords = recordService.queryWalletRecord(mechanismId, page, limit, sort, order);
        int total = recordService.countelective(mechanismId, page, limit, sort, order);
        Map<String, Object> data = new HashMap<>(3);
        data.put("total", total);
        data.put("items", walletRecords);
        data.put("remindValue", SystemConfig.getChongzhiRemindValue());
        return ResponseUtil.ok(data);

    }

    @GetMapping("/username")
    public Object username(String username) {
        if (StringUtil.isEmpty(username)) {
            return ResponseUtil.badArgument();
        }

        int total = userService.countSeletive(username, null, null, null, null, null);
        if (total == 0) {
            return ResponseUtil.ok("不存在");
        }
        return ResponseUtil.ok("已存在");
    }

    /**
     * 创建用户
     */
    @PostMapping("/creates")
    public Object create(@LoginAdmin Integer adminId, @RequestBody LitemallUser user) {
        LitemallUser userCheck = userService.findByMobile(user.getMobile());
        if(userCheck == null){
            logger.debug(user);
            user.setAddTime(LocalDateTime.now());
            String password = CharUtil.getRandomNum(6);
            String payPassword = CharUtil.getRandomNum(6);
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodedPassword = encoder.encode(password);
            String encodedPayPassword = encoder.encode(payPassword);
            user.setPassword(encodedPassword);
            user.setPayPassword(encodedPayPassword);
            userService.add(user);
            //发送短信通知
            new Thread(()-> {
                    String params = new String("{\"username\":\"" + user.getUsername() + "\",\"password\":\"" + password + "\",\"paypassword\":\"" + payPassword + "\"}");
                    notifyService.notifySmsTemplateSync(user.getMobile(), NotifyType.CREATEUSER, params);
            }).start();

            return ResponseUtil.ok(user);
        }else{
            return ResponseUtil.ok("fail");
        }

    }

    /**
     * 支付5元人工处理费
     * @return 二维码
     */
    @PostMapping("/payfive")
    public Object payfive(@LoginAdmin Integer adminId, @RequestBody LitemallWalletRecord walletRecord){
        //创建机构支付的钱包记录
        logger.debug(walletRecord);
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        walletRecord.setPayType((byte)2);
        walletRecord.setType((byte)2);
        walletRecord.setModifyReason("充错号码调整");
        walletRecord.setModifyAmount(new BigDecimal(-5));
        walletRecord.setMechaismId(walletRecord.getModifyResource());
        walletRecord.setPayType((byte)2);
        walletRecord.setModifyTime(LocalDateTime.now());
        walletRecord.setActualPayment(new BigDecimal(5));
        if(walletRecord.getRecordSn()!=null){
            recordService.add(walletRecord);
        }else {
            return ResponseUtil.fail();
        }
        WxPayService wxPayServices = getWxPayService.getWxPay();
        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setProductId(walletRecord.getId().toString());
        orderRequest.setOutTradeNo(walletRecord.getRecordSn());
        orderRequest.setBody("充错号码调整");
        WxPayUnifiedOrderResult result = null;
        try {
            Integer fee = 500;
            orderRequest.setTotalFee(fee);
            orderRequest.setSpbillCreateIp(InetAddress.getLocalHost().getHostAddress());
            orderRequest.setTradeType("NATIVE");
            result = wxPayServices.unifiedOrder(orderRequest);
        }
        catch (UnknownHostException e) {
            e.printStackTrace();
        }
        catch (WxPayException e) {
            e.printStackTrace();
        }
        return ResponseUtil.ok(result);
    }

    /**
     * method: returnFiveWxPayStatus
     *
     * 微信支付成功回调结果 充值成功后,更新充值记录
     */
    @PostMapping("/returnFiveWxPayStatus")
    public void  returnFiveWxPayStatus(HttpServletResponse response, HttpServletRequest request) throws Exception {
        Map<String, String> map = ParseXmlUtil.parseXml(request);
        WxPlaceOrder wxPlaceOrder = new WxPlaceOrder();
        String   trade_status =    map.get("return_code");
        String out_trade_no ;
        if(trade_status.equals(WxTradeStatus.SUCCESS)){
            if(map.get("result_code").equals(WxTradeStatus.SUCCESS)){
                out_trade_no =   map.get("out_trade_no");
                String trade_no =   map.get("transaction_id");
                LitemallWalletRecord litemallWalletRecord = recordService.queryByRecordSn(out_trade_no);
                if(litemallWalletRecord != null){
                    if(litemallWalletRecord.getPayId() == null){
                        litemallWalletRecord.setPayId(trade_no);
                        litemallWalletRecord.setPayTime(LocalDateTime.now());
                        recordService.update(litemallWalletRecord);
                    }
                }
            }
            // 通知成功
            wxPlaceOrder.setReturn_code("SUCCESS");
            XStream xStream = new XStream(new StaxDriver(new NoNameCoder()));
            xStream.alias("xml", WxPlaceOrder.class);
            String returnXml = xStream.toXML(wxPlaceOrder);
            try {
                response.getWriter().write(returnXml);
            } catch (IOException e) {
                logger.info("通知回调 微信服务器 异常:"+ e);
            }
        }
    }

    /**
     * method: 机构为用户充值积分
     *
     * @Description: 1、添加用户充值记录
     * <p>
     * 2、付款成功后给用户增加积分
     * 3、付款成功后扣除机构积分额度
     * @param: [adminId, walletRecord]
     * @return: java.lang.Object
     * @author: yh
     * @date: 2018/7/16 0:15
     */
    @PostMapping("/create")
    public Object create(
        @LoginAdmin Integer adminId, @RequestBody LitemallWalletRecord walletRecord, HttpServletRequest request, HttpServletResponse response) {
        logger.debug(walletRecord);
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        int modifyIntegral = walletRecord.getModifyIntegral();//充值的积分
        LitemallMechanism mechanism = mechanismService.findById(walletRecord.getModifyResource());
        Long integralUsed = mechanism.getIntegralAmountUsed();
        Long integralAll = mechanism.getIntegralAmountAll();

        // 实时根据积分与爱币的比值计算爱币的值
        String level = mechanism.getLevel()==null ? "":mechanism.getLevel().toString();
        LitemallConfig integralToANBConfig;
        if(!StringUtils.isEmpty(level)&&"1".equals(level)){
            integralToANBConfig = configService.findById(10000008);
        }else {
            integralToANBConfig = configService.findById(10000002);
        }
        Double integralToANBValue = Double.parseDouble(integralToANBConfig.getValue());
        if (integralUsed >= integralAll) {
            integralToANBValue = integralToANBValue + 0.01;
        }
        LitemallConfig ANBToRMBConfig = configService.findById(10000001);
        Double ANBToRMBValue = Double.parseDouble(ANBToRMBConfig.getValue());

        BigDecimal anb = new BigDecimal(integralToANBValue).multiply(new BigDecimal(modifyIntegral)).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal rmb = new BigDecimal(ANBToRMBValue).multiply(anb).setScale(2, BigDecimal.ROUND_HALF_UP);
        if (rmb.compareTo(new BigDecimal(0.01)) < 0) {
            //不足1分按1分计算
            rmb = new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        WxPayUnifiedOrderResult result = null;
        try {
            //1、添加用户充值记录
            walletRecord.setModifyAmount(new BigDecimal(0));
            walletRecord.setModifyTime(LocalDateTime.now());
            walletRecord.setActualPayment(rmb);
            recordService.add(walletRecord);
            Integer walletRecordId =walletRecord.getId();
            if(walletRecordId == null){
                return ResponseUtil.fail(-1, "订单创建失败，请重新操作！");
            }

            Integer recordId = walletRecord.getId();

            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setProductId(recordId.toString());
            orderRequest.setOutTradeNo(walletRecord.getRecordSn());
            orderRequest.setBody("充值：" + walletRecord.getModifyReason());
            // 元转成分
            Integer fee = 0;
            fee = rmb.multiply(new BigDecimal(100)).intValue();
            orderRequest.setTotalFee(fee);
            orderRequest.setSpbillCreateIp(InetAddress.getLocalHost().getHostAddress());
            orderRequest.setTradeType("NATIVE");
            result = wxPayService.unifiedOrder(orderRequest);

        }
        catch (Exception ex) {
            txManager.rollback(status);
            logger.error("支付出错！", ex);
        }
        txManager.commit(status);
        return ResponseUtil.ok(result);
    }

    @PostMapping("/update")
    public Object update(@LoginAdmin Integer adminId, @RequestBody LitemallUser user) {
        logger.debug(user);
        userService.update(user);
        return ResponseUtil.ok(user);
    }

    @GetMapping("/detail")
    public Object detail(@LoginAdmin Integer adminId, String mobile) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        if (mobile == null) {
            return ResponseUtil.badArgument();
        }

        LitemallUser user = userService.findByMobile(mobile);
        int num = userService.num(mobile);
        Map<String, Object> data = new HashMap<>();
        data.put("user", user);
        data.put("num", num);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/checkusername")
    public Object checkUserName(@LoginAdmin Integer adminId, String userName) {
        boolean validFlag = false;
        List<LitemallUser> userList = userService.queryByUsername(userName);
        if (userList.size() >= 1) {
            validFlag = false;
        } else if (userList.size() == 0) {
            validFlag = true;
        }
        Map<String, Object> data = new HashMap<>();
        data.put("validFlag", validFlag);
        return ResponseUtil.ok(data);
    }

    /**
     * method: checkChargeStatus
     *
     * @Description:检查充值支付结果 充值成功后1、更新充值记录 2、给用户增加积分
     * @param: [adminId, orderSn]
     * @return: java.lang.Object
     * @author: yh
     * @date: 2018/7/17 22:44
     */
    @GetMapping("/checkchargestatus")
    public Object checkChargeStatus(@LoginAdmin Integer adminId, String orderSn) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Map<String, Object> data = new HashMap<>();
        try {
            WxPayOrderQueryResult orderQueryResult = wxPayService.queryOrder("", orderSn);
            String returnCode = orderQueryResult.getReturnCode();
            String resultCode = orderQueryResult.getResultCode();
            String tradeState = orderQueryResult.getTradeState();
            if (returnCode.equals("SUCCESS") && resultCode.equals("SUCCESS") && tradeState.equals("SUCCESS")) {
                data.put("orderStatus", "SUCCESS");
                // 开启事务管理
                LitemallWalletRecord walletRecord = recordService.queryByRecordSn(orderSn);
                DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                TransactionStatus status = txManager.getTransaction(def);
                try {
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                    LocalDateTime ldt = LocalDateTime.parse(orderQueryResult.getTimeEnd(), df);
                    walletRecord.setPayId(orderQueryResult.getTransactionId());
                    walletRecord.setPayTime(ldt);
                    recordService.update(walletRecord);

                    LitemallUser user = userService.findById(walletRecord.getUserId());
                    int lastIntegral = user.getIntegral() + walletRecord.getModifyIntegral();
                    user.setIntegral(lastIntegral);
                    if (user.getFirstMechanism() == null) {
                        user.setFirstMechanism(walletRecord.getModifyResource());
                    }
                    userService.update(user);
                    // 3、充值成功扣除机构积分额度
                    LitemallMechanism mechanism = mechanismService.findById(walletRecord.getModifyResource());
                    mechanism.setIntegralAmountUsed(mechanism.getIntegralAmountUsed() + walletRecord.getModifyIntegral());
                    mechanismService.updateById(mechanism);
                    //短信通知用户充值信息
                    if (user.getMobile() != null && !user.getMobile().equals("")) {
                        String params =
                            new String("{\"mechanism\":\"" + mechanism.getName() + "\",\"username\":\"" + user.getUsername() + "\",\"integral\":\"" + walletRecord.getModifyIntegral() + "\"}");
                        notifyService.notifySmsTemplateSync(user.getMobile(), NotifyType.GIVENOTIGY, params);
                    }

                }
                catch (Exception ex) {
                    txManager.rollback(status);
                    logger.error("支付出错！", ex);
                }
                txManager.commit(status);
            } else {
                data.put("orderStatus", "FAIL");
            }
        }
        catch (WxPayException e) {
            e.printStackTrace();
            logger.error(e);
        }
        return ResponseUtil.ok(data);
    }

    @GetMapping("/checkchargestatuss")
    public Object checkChargeStatus( String orderSn) {

        Map<String, Object> data = new HashMap<>();
        try {
            WxPayOrderQueryResult orderQueryResult = wxPayService.queryOrder("", orderSn);
            String returnCode = orderQueryResult.getReturnCode();
            String resultCode = orderQueryResult.getResultCode();
            String tradeState = orderQueryResult.getTradeState();
            if (returnCode.equals("SUCCESS") && resultCode.equals("SUCCESS") && tradeState.equals("SUCCESS")) {
                data.put("orderStatus", "SUCCESS");
                // 开启事务管理

            } else {
                data.put("orderStatus", "FAIL");
            }
        }
        catch (WxPayException e) {
            e.printStackTrace();
            logger.error(e);
        }
        return ResponseUtil.ok(data);
    }

    /**
     * 支付宝充值
     */
    @PostMapping("/chargebyalipay")
    public Object chargeByAliPay(@LoginAdmin Integer adminId, @RequestBody LitemallWalletRecord walletRecord, HttpServletRequest request, HttpServletResponse response) {
        logger.debug(walletRecord);
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        //充值的积分
        int modifyIntegral = walletRecord.getModifyIntegral();
        LitemallMechanism mechanism = mechanismService.findById(walletRecord.getModifyResource());
        Long integralUsed = mechanism.getIntegralAmountUsed();
        Long integralAll = mechanism.getIntegralAmountAll();

        // 获得机构的等级
        String level = mechanism.getLevel()==null ? "":mechanism.getLevel().toString();
        LitemallConfig integralToANBConfig;
        if(!StringUtils.isEmpty(level)&&"1".equals(level)){
            integralToANBConfig = configService.findById(10000008);
        }else {
            integralToANBConfig = configService.findById(10000002);
        }
        // 实时根据积分与爱币的比值计算爱币的值

        Double integralToANBValue = Double.parseDouble(integralToANBConfig.getValue());
        if (integralUsed >= integralAll) {
            integralToANBValue = integralToANBValue + 0.01;
        }
        LitemallConfig ANBToRMBConfig = configService.findById(10000001);
        Double ANBToRMBValue = Double.parseDouble(ANBToRMBConfig.getValue());

        BigDecimal anb = new BigDecimal(integralToANBValue).multiply(new BigDecimal(modifyIntegral)).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal rmb = new BigDecimal(ANBToRMBValue).multiply(anb).setScale(2, BigDecimal.ROUND_HALF_UP);
        if (rmb.compareTo(new BigDecimal(0.01)) < 0) {
            //不足1分按1分计算
            rmb = new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        AlipayTradePrecreateResponse res ;
        try {
            //1、添加用户充值记录
            walletRecord.setModifyAmount(new BigDecimal(0));
            walletRecord.setModifyTime(LocalDateTime.now());
            walletRecord.setActualPayment(rmb);
            recordService.add(walletRecord);
            Integer mechanismId = walletRecord.getModifyResource();

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = walletRecord.getRecordSn();
            //付款金额，必填
            String total_amount = rmb.toString();
//            String total_amount = "0.01";
            //订单名称，必填
            String subject = new String(walletRecord.getModifyReason().getBytes("UTF-8"), "UTF-8");
            //商品描述，可空
            String body = new String("");
            //            String sign_type = "RSA2";
            String timeoutExpress = "15m";

            ExtendParams extendParams = new ExtendParams();
            extendParams.setSysServiceProviderId(aliPayProperties.getPid());

            AlipayTradePrecreateRequestBuilder builder =
                new AlipayTradePrecreateRequestBuilder().setSubject(subject).setTotalAmount(total_amount).setOutTradeNo(out_trade_no).setBody(body).setTimeoutExpress(timeoutExpress)
                    .setAppAuthToken(aliPayProperties.getAppAuthToken()).setStoreId(mechanismId.toString())
                    //支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
                    .setNotifyUrl(aliPayProperties.getNotifyUrl()).setExtendParams(extendParams);
            AlipayF2FPrecreateResult preCreateResult = alipayTradeService.tradePrecreate(builder);
            switch (preCreateResult.getTradeStatus()) {
                case SUCCESS:
                    res = preCreateResult.getResponse();
                    break;
                case FAILED:
                case UNKNOWN:
                    return ResponseUtil.fail(-1, "支付宝预下单失败");
                default:
                    return ResponseUtil.fail(-1, "支付宝预下单失败");
            }
        }
        catch (Exception ex) {
            txManager.rollback(status);
            logger.error("支付出错！", ex);
            return ResponseUtil.fail(-1, "支付出错!");
        }
        txManager.commit(status);
        return ResponseUtil.ok(res.getQrCode());
    }


    /**
     * method: checkChargeStatus
     *
     * @Description:检查充值支付结果 充值成功后1、更新充值记录 2、给用户增加积分
     * @param: [adminId, orderSn]
     * @return: java.lang.Object
     * @author: yh
     * @date: 2018/7/17 22:44
     */
    @GetMapping("/checkalipaystatus")
    public Object checkAliPayStatus(@LoginAdmin Integer adminId, String orderSn) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Map<String, Object> data = new HashMap<>();
        try {
            AlipayTradeQueryRequestBuilder builder = new AlipayTradeQueryRequestBuilder().setOutTradeNo(orderSn).setAppAuthToken(aliPayProperties.getAppAuthToken());
            AlipayF2FQueryResult queryResult = alipayTradeService.queryTradeResult(builder);
            System.out.println(queryResult);
            AlipayTradeQueryResponse response = queryResult.getResponse();
            switch (queryResult.getTradeStatus()) {
                case SUCCESS:
                    System.out.println("查询返回该订单支付成功:");
                    //                log.info(resp.getFundBillList());
                    if (response.getTradeStatus().equals("TRADE_SUCCESS") || response.getTradeStatus().equals("TRADE_FINISHED")) {
//                        System.out.println("支付成功");
                        data.put("orderStatus", "SUCCESS");
                        // 开启事务管理
                        LitemallWalletRecord walletRecord = recordService.queryByRecordSn(orderSn);
                        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                        TransactionStatus status = txManager.getTransaction(def);
                        try {
                            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                            LocalDateTime ldt = LocalDateTime.ofInstant(response.getSendPayDate().toInstant(), ZoneId.systemDefault());
                            walletRecord.setPayId(response.getTradeNo());
                            walletRecord.setPayTime(ldt);
                            recordService.update(walletRecord);

                            LitemallUser user = userService.findById(walletRecord.getUserId());
                            int lastIntegral = user.getIntegral() + walletRecord.getModifyIntegral();
                            user.setIntegral(lastIntegral);
                            if (user.getFirstMechanism() == null) {
                                user.setFirstMechanism(walletRecord.getModifyResource());
                            }
                            userService.update(user);
                            // 3、充值成功扣除机构积分额度
                            LitemallMechanism mechanism = mechanismService.findById(walletRecord.getModifyResource());
                            mechanism.setIntegralAmountUsed(mechanism.getIntegralAmountUsed() + walletRecord.getModifyIntegral());
                            mechanismService.updateById(mechanism);
                            //短信通知用户充值信息
                            if (user.getMobile() != null && !user.getMobile().equals("")) {
                                String params =
                                    new String("{\"mechanism\":\"" + mechanism.getName() + "\",\"username\":\"" + user.getUsername() + "\",\"integral\":\"" + walletRecord.getModifyIntegral() + "\"}");
                                notifyService.notifySmsTemplateSync(user.getMobile(), NotifyType.GIVENOTIGY, params);
                            }
                        }
                        catch (Exception ex) {
                            txManager.rollback(status);
                            logger.error("支付出错！", ex);
                            return ResponseUtil.fail();
                        }
                        txManager.commit(status);
                    } else if (response.getTradeStatus().equals("WAIT_BUYER_PAY")) {
//                        System.out.println("等待成功");
                        data.put("orderStatus", "WAIT_PAY");
                    } else {
                        data.put("orderStatus", "FAIL");
                    }
                    break;
                case FAILED:
                    // log.error("查询返回该订单支付失败!!!");
                    data.put("orderStatus", "WAIT_PAY");
                    break;
                case UNKNOWN:
                    //                    log.error("系统异常，订单支付状态未知!!!");
                    return ResponseUtil.fail(-1, "系统异常，订单支付状态未知!!!");
                default:
                    //                    log.error("不支持的交易状态，交易返回异常!!!");
                    return ResponseUtil.fail(-1, "不支持的交易状态，交易返回异常!!!");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok(data);
    }



    /**
     * method: checkChargeStatus
     *
     * @Description:检查充值支付结果 充值成功后1、更新充值记录 2、给用户增加积分
     * @param: [adminId, orderSn]
     * @return: java.lang.Object
     * @author: yh
     * @date: 2018/7/17 22:44
     */
    @GetMapping("/queryalipaystatus")
    public Object queryalipaystatus(@LoginAdmin Integer adminId, String orderSn) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Map<String, Object> data = new HashMap<>(1);
        LitemallWalletRecord walletRecord = recordService.queryByRecordSn(orderSn);
        String  payid =  walletRecord.getPayId();
        if(org.apache.commons.lang.StringUtils.isNotBlank(payid)){
            data.put("orderStatus", "SUCCESS");
        }else{
            data.put("orderStatus", "WAIT_PAY");
        }

        return ResponseUtil.ok(data);
    }



    /**
     * method: checkChargeStatus
     *
     * @Description:支付宝支付成功回调结果 充值成功后1、更新充值记录 2、给用户增加积分
     * @param: [adminId, orderSn]
     * @return: java.lang.Object
     * @author: lj
     * @date: 2018/7/17 22:44
     */
    @PostMapping("/returnAliPayStatus")
    public String  returnAliPayStatus( HttpServletRequest request) {
        String out_trade_no ;
        try {
            String  trade_status = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
            if(trade_status.equals(AliTradeStatus.TRADE_SUCCESS)  || trade_status.equals(AliTradeStatus.TRADE_FINISHED) ){
                out_trade_no = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
                String trade_no = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
                String gmt_payment = new String(request.getParameter("gmt_payment").getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
                SimpleDateFormat ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date ds = ss.parse(gmt_payment);
                LitemallWalletRecord litemallWalletRecord = recordService.queryByRecordSn(out_trade_no);
                if(litemallWalletRecord != null){
                    if(litemallWalletRecord.getPayId() == null){
                        litemallWalletRecord.setPayId(trade_no);
                        LocalDateTime ldt = LocalDateTime.ofInstant(ds.toInstant(), ZoneId.systemDefault());
                        litemallWalletRecord.setPayTime(ldt);
                        recordService.update(litemallWalletRecord);

                        if(litemallWalletRecord.getType() == 1){
                            LitemallUser user = userService.findById(litemallWalletRecord.getUserId());
                            int lastIntegral = user.getIntegral() + litemallWalletRecord.getModifyIntegral();
                            user.setIntegral(lastIntegral);
                            if (user.getFirstMechanism() == null) {
                                user.setFirstMechanism(litemallWalletRecord.getModifyResource());
                            }
                            userService.update(user);
                            // 3、充值成功扣除机构积分额度
                            LitemallMechanism mechanism = mechanismService.findById(litemallWalletRecord.getModifyResource());
                            mechanism.setIntegralAmountUsed(mechanism.getIntegralAmountUsed() + litemallWalletRecord.getModifyIntegral());
                            mechanismService.updateById(mechanism);
                            //短信通知用户充值信息
                            if (org.apache.commons.lang.StringUtils.isNotBlank(user.getMobile())) {
                                String params =
                                        new String("{\"mechanism\":\"" + mechanism.getName() + "\",\"username\":\"" + user.getUsername() + "\",\"integral\":\"" + litemallWalletRecord.getModifyIntegral() + "\"}");
                                notifyService.notifySmsTemplateSync(user.getMobile(), NotifyType.GIVENOTIGY, params);
                            }
                        }
                        if(litemallWalletRecord.getType() == 6){
                            LitemallOrder order = litemallOrderService.queryByOrderSn(out_trade_no);
                            order.setPayId(trade_no);
                            order.setPayTime(ldt);
                            order.setOrderStatus(OrderUtil.STATUS_PAY);
                            litemallOrderService.update(order);
                        }
                        return SUCCESS;
                        }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return "failure";
        }
        return "";
    }


    /**
     * method: checkChargeStatus
     *
     * @Description:微信支付成功回调结果 充值成功后1、更新充值记录 2、给用户增加积分
     * @param: [adminId, orderSn]
     * @return: java.lang.Object
     * @author: lj
     * @date: 2018/7/17 22:44
     */
    @PostMapping("/returnWxPayStatus")
    public void  returnWxPayStatus(HttpServletResponse response, HttpServletRequest request) throws Exception {
       logger.info("有请求：returnWxPayStatus");
        Map<String, String> map = ParseXmlUtil.parseXml(request);
        WxPlaceOrder wxPlaceOrder = new WxPlaceOrder();
        String   trade_status =    map.get("return_code");
        String out_trade_no ;
            if(trade_status.equals(WxTradeStatus.SUCCESS)){
                if(map.get("result_code").equals(WxTradeStatus.SUCCESS)){
                    out_trade_no =   map.get("out_trade_no");
                    String trade_no =   map.get("transaction_id");
                    LitemallWalletRecord litemallWalletRecord = recordService.queryByRecordSn(out_trade_no);
                    if(litemallWalletRecord != null){
                        if(litemallWalletRecord.getPayId() == null){
                            litemallWalletRecord.setPayId(trade_no);
                            litemallWalletRecord.setPayTime(LocalDateTime.now());
                            recordService.update(litemallWalletRecord);

                            if(litemallWalletRecord.getType() == 1){
                                LitemallUser user = userService.findById(litemallWalletRecord.getUserId());
                                int lastIntegral = user.getIntegral() + litemallWalletRecord.getModifyIntegral();
                                user.setIntegral(lastIntegral);
                                if (user.getFirstMechanism() == null) {
                                    user.setFirstMechanism(litemallWalletRecord.getModifyResource());
                                }
                                userService.update(user);
                                // 3、充值成功扣除机构积分额度
                                LitemallMechanism mechanism = mechanismService.findById(litemallWalletRecord.getModifyResource());
                                mechanism.setIntegralAmountUsed(mechanism.getIntegralAmountUsed() + litemallWalletRecord.getModifyIntegral());
                                mechanismService.updateById(mechanism);
                                //短信通知用户充值信息
                                if (org.apache.commons.lang.StringUtils.isNotBlank(user.getMobile())) {
                                    String params =
                                            new String("{\"mechanism\":\"" + mechanism.getName() + "\",\"username\":\"" + user.getUsername() + "\",\"integral\":\"" + litemallWalletRecord.getModifyIntegral() + "\"}");
                                    notifyService.notifySmsTemplateSync(user.getMobile(), NotifyType.GIVENOTIGY, params);
                                }
                            }
                            if(litemallWalletRecord.getType() == 6){
                                LitemallOrder order = litemallOrderService.queryByOrderSn(out_trade_no);
                                order.setPayId(trade_no);
                                order.setPayTime(LocalDateTime.now());
                                order.setOrderStatus(OrderUtil.STATUS_PAY);
                                litemallOrderService.update(order);
                            }

                        }
                    }
                }
                // 通知成功
                wxPlaceOrder.setReturn_code("SUCCESS");
                XStream xStream = new XStream(new StaxDriver(new NoNameCoder()));
                xStream.alias("xml", WxPlaceOrder.class);
                String returnXml = xStream.toXML(wxPlaceOrder);
                try {
                    response.getWriter().write(returnXml);
                } catch (IOException e) {
                    logger.info("通知回调 微信服务器 异常:"+ e);
                }
            }
    }



}